package cn.itsource.controller;

import cn.itsource.constant.SystemConstant;
import cn.itsource.domain.Param;
import cn.itsource.domain.User;
import cn.itsource.query.ParamQuery;
import cn.itsource.service.ParamService;
import cn.itsource.util.AjaxResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 接口类：博客参数Param
 */
@RestController
@RequestMapping("/param")
public class ParamController {

    @Autowired
    private ParamService paramService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public List<Param> findAll(){
        return paramService.findAll();
    }

    /**
     * 查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Param findOne(@PathVariable("id")Long id){
        return paramService.findOne(id);
    }

    /**
     * 添加和修改
     * @param param
     * @return
     */
    @PutMapping
    public AjaxResult addorUpdate(@RequestBody Param param, HttpSession session){
        User user = (User)session.getAttribute(SystemConstant.USER_IN_SESSION);
        param.setOperatorName(user.getUserName());
        try {
            if(param.getId()==null){//添加操作
                paramService.add(param);
            }else{
                paramService.update(param);
            }
            //如果成功
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id")Long id){
        try {
            paramService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }

    /**
     * 分页查询 + 高级查询
     * @param query
     * @return
     */
    @PostMapping
    public PageInfo<Param> pageQuery(@RequestBody ParamQuery query){
        return paramService.pageQuery(query);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids){  //["2","14"] - Long[] ids
        try {
            paramService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }

    /**
     * 前台：获取博客参数
     * @return
     */
    @GetMapping("/getParams")
    public Map<String,String> getParams(){
        return paramService.getParams();
    }

}
